/*
 * Copyright (c) 2011 Martin Farrell (farrelmr@gmail.com)
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc., 51
 * Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <QString>
#include <QDebug>
#include <QDateTime>

#include "routeviewergui.h"
#include "ui_routeviewergui.h"

#include "RealtimeData.h"
#include "ant.h"
#include "math.h"

// define ROUTEVIEWER_INIT_URL     "http://127.0.0.1:8888/ant?action=startrv"
// define ROUTEVIEWER_PAIRING_URL  "http://127.0.0.1:8888/index.jsp?gwt.codesvr=127.0.0.1:9997&pairingid=11111"
// define ROUTEVIEWER_RUNNING_URL  "http://127.0.0.1:8888   /ant?action=ant&v=0&speedms=%1&cadence=%2&hrm=%3&watts%4&wheelrpm=%5&wheelsizemm=%6&quarqid=%7&time=%8"

#define ROUTEVIEWER_INIT_URL     "http://www.routeviewer.com/ant?action=startrv"
#define ROUTEVIEWER_PAIRING_URL  "http://www.routeviewer.com/index.jsp?pairingid=%1"
#define ROUTEVIEWER_RUNNING_URL  "http://www.routeviewer.com/ant?action=ant&v=0&speedms=%1&cadence=%2&hrm=%3&watts%4&wheelrpm=%5&wheelsizemm=%6&quarqid=%7&time=%8"

routeviewerGUI::routeviewerGUI(QWidget *parent) : QWidget(parent) {
	
	ui.setupUi(this);

	displayUnits = 0; // kmph
	
    status = 0;
    status |= RT_MODE_ERGO; // ergo mode by default
        
    myANTlocalController = new ANTlocalController(this, &deviceConfiguration);
    
	// init timer
	gui_timer = new QTimer(this);

	connect(gui_timer, SIGNAL(timeout()), this, SLOT(guiUpdate_ontimer()));

	ROUTEVIEWER_HTTP_STATUS = ROUTEVIEWER_HTTP_STATUS_INIT;

	qNetworkAccessManager = new QNetworkAccessManager(this);

	QObject::connect(qNetworkAccessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(finishedSlot(QNetworkReply*)));

	QString url = QString( ROUTEVIEWER_INIT_URL);
	
	QNetworkReply* reply = qNetworkAccessManager->get(QNetworkRequest(url));

}

routeviewerGUI::~routeviewerGUI() {
}

// convert from kmph to mph
void routeviewerGUI::on_changeUnits_clicked() {
	if (displayUnits == 0) {
		ui.unitsPushButton->setText(QApplication::translate("routeviewer",
				"kmph", 0, QApplication::UnicodeUTF8));
		ui.label->setText(QApplication::translate("routeviewer", "mph", 0,
				QApplication::UnicodeUTF8));
		displayUnits = 1; // show mph
	} else {
		ui.unitsPushButton->setText(QApplication::translate("routeviewer",
				"mph", 0, QApplication::UnicodeUTF8));
		ui.label->setText(QApplication::translate("routeviewer", "kmh", 0,
				QApplication::UnicodeUTF8));
		displayUnits = 0; // show kmph
	}
}

// start routeviewer client - RealtimeWindow::Start()
void routeviewerGUI::on_startrv_clicked() {
	
    if (status&RT_RUNNING) {
       return;
    } else {    	
       
       if ( ROUTEVIEWER_HTTP_STATUS == ROUTEVIEWER_HTTP_STATUS_NO_BROWSER_RUNNING) {
          pairingUrl = QString(ROUTEVIEWER_PAIRING_URL).arg(pairingId);
          QDesktopServices::openUrl( QUrl(pairingUrl) );
          ROUTEVIEWER_HTTP_STATUS = ROUTEVIEWER_HTTP_STATUS_RUNNING;
       }
       
       deviceConfiguration = DeviceConfiguration();
       myANTlocalController = new ANTlocalController (this, &deviceConfiguration);
       if ( myANTlocalController == NULL ) {
    	   return;
       } else {
    	   myANTlocalController->start();
    	   gui_timer->start(REFRESHRATE); // start recording
    	   
           // we're away!
           status |= RT_RUNNING;
       }
    }
    
}

// RealtimeWindow::Stop
void routeviewerGUI::on_stoprv_clicked() {
	
    if (myANTlocalController == NULL) return;
	
    if ((status&RT_RUNNING) == 0) return;
    
    status &= ~RT_RUNNING;
	
    // wipe connection
    myANTlocalController->stop();
    delete myANTlocalController;
    myANTlocalController = NULL;
    
    gui_timer->stop();
    
    guiUpdate_ontimer();
    
}

void routeviewerGUI::guiUpdate_ontimer() // refreshes the telemetry
{
	if (myANTlocalController == NULL) {

		ui.speedLcdNumber->display( 0.0 );
		ui.cadenceLcdNumber->display( 0 );
		ui.hrLcdNumber->display( 0 );
		ui.powerLcdNumber->display( 0 );		
		
		return;

	} else {

		double wheelSizeMM = ui.wheelSizeMMSpinBox->value();		
		
		if ( status&RT_RUNNING ) {

			myANTlocalController->getRealtimeData(rtData);
						
			int currentTimeRecord = rtData.getTime();
			
			if ( currentTimeRecord != lastRealTimeRecord ) {
  			   lastRealTimeRecord = rtData.getTime();
  			   currentTimeRecord  = lastRealTimeRecord;

   			   double speedMS = (rtData.getWheelRpm() / 60.0) * (wheelSizeMM / 1000); // ms

			   speedVal = 0.0d; // round(displaySpeed * (useMetricUnits ? 1.0 : MILES_PER_KM) * 10.00)/10.00;
			   if (displayUnits == 0) {
			  	  speedVal = round(speedMS * 10.00) / 10.00; // kmph speedKmph = speedMeterPerSecond * 3.6; // * 3600) / 1000
			   } else {
				  speedVal = round(speedMS * 6.2137119) / 10.00; // mph - speedMph = speedKmph * 0.62150404; // * / 1.609;
			   }

			   ui.speedLcdNumber->display(QString::number(speedVal, 'f', 1));
			   ui.cadenceLcdNumber->display(round(rtData.getCadence() ) );
			   ui.hrLcdNumber->display(round(rtData.getHr() ) );
			   ui.powerLcdNumber->display(round(rtData.getWatts() ) );

			   // Post to routeviewer
			   QString runningUrl = QString(ROUTEVIEWER_RUNNING_URL).arg( speedMS ).arg( rtData.getCadence() ).arg( rtData.getHr() ).arg( rtData.getWatts() ).arg( rtData.getWheelRpm() ).arg( wheelSizeMM ).arg( pairingId ).arg( currentTimeRecord );
			
//		 	   qWarning( runningUrl.toLatin1() );
			
			   QNetworkReply* reply = qNetworkAccessManager->get(QNetworkRequest(runningUrl));
			   
			} else {
				
			   ui.speedLcdNumber->display( 0.0 );
			   ui.cadenceLcdNumber->display( 0 );
			   ui.hrLcdNumber->display( 0 );
			   ui.powerLcdNumber->display( 0 );	
				
			   // Post to routeviewer
			   QString runningUrl = QString(ROUTEVIEWER_RUNNING_URL).arg( 0.0 ).arg( 0 ).arg( rtData.getHr() ).arg( 0 ).arg( 0 ).arg( wheelSizeMM ).arg( pairingId ).arg( (int) QDateTime::currentMSecsSinceEpoch() );
				
//			   qWarning( runningUrl.toLatin1() );
				
			   QNetworkReply* reply = qNetworkAccessManager->get(QNetworkRequest(runningUrl));
				
			}
			
		} else {
			
			ui.speedLcdNumber->display( 0.0 );
			ui.cadenceLcdNumber->display( 0 );
			ui.hrLcdNumber->display( 0 );
			ui.powerLcdNumber->display( 0 );	
			
			// Post to routeviewer
			QString runningUrl = QString(ROUTEVIEWER_RUNNING_URL).arg( 0.0 ).arg( 0 ).arg( rtData.getHr() ).arg( 0 ).arg( 0 ).arg( wheelSizeMM ).arg( pairingId ).arg( (int) QDateTime::currentMSecsSinceEpoch() );
			
//		 	qWarning( runningUrl.toLatin1() );
			
			QNetworkReply* reply = qNetworkAccessManager->get(QNetworkRequest(runningUrl));
			
		}

	}

}

void routeviewerGUI::finishedSlot(QNetworkReply *reply) {
	if (!reply->error()) {
		if (ROUTEVIEWER_HTTP_STATUS == ROUTEVIEWER_HTTP_STATUS_INIT) {

			pairingUrl = QString(ROUTEVIEWER_PAIRING_URL).arg(pairingId);
//			QDesktopServices::openUrl(QUrl(pairingUrl));
			
			pairingId = reply->readAll();
			
			pairingId = pairingId.trimmed();
			
			ui.routeviewerLineEdit->setText(pairingId);

			ROUTEVIEWER_HTTP_STATUS = ROUTEVIEWER_HTTP_STATUS_NO_BROWSER_RUNNING;

		}
	}

	// We receive ownership of the reply object and therefore need to handle deletion.
	delete reply;
}